package website.lucaswork.survey.mvc.utils;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.multipart.MultipartFile;
import website.lucaswork.survey.core.utils.DefaultValues;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Component
public class FileUtil {

    private final static String UPLOAD_PATH = "upload";

    @Autowired
    private HttpServletRequest request;

    @Autowired
    DefaultValues defaultValues;

    public String uploadToLocal(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty()) {
            return "";
        }
        String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        Resource folder = new ServletContextResource(request.getSession().getServletContext(), "./" + UPLOAD_PATH);
        File targetFile = File.createTempFile("pic", extension, folder.getFile());
        try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(targetFile)) {
            IOUtils.copy(in, out);
        }
        return defaultValues.getBackendUrl() + UPLOAD_PATH + "/" + targetFile.getName();
    }
}
